/*
 * @Author: TuYongTao
 * @Date: 2021-10-29 18:35:25
 * @LastEditors: your Name
 * @LastEditTime: 2021-10-29 18:59:11
 * @Description: 
 */

import Dep from './dep.js'
export default class Observer {
  constructor(data) {
    this.walk(data)
  }
  walk(data) {
    if (!data || typeof data !== 'object') {
      return
    }
    Object.keys(data).forEach((key) => {
      // 响应式
      this.defineReactive(data, key, data[key])
    })
  }

  defineReactive(data, key, value) {
    this.walk(value)
    let self = this
    let dep = new Dep()
    Object.defineProperty(data, key, {
      // 设置可枚举
      enumerable: true,
      // 设置可配置
      configurable: true,
      // 获取值
      get() {
        Dep.target && dep.addSub(Dep.target)
        return value
      },
      set(newValue) {
        // 判断旧值和新值是否相等
        if (newValue === value) return
        // 设置新值
        value = newValue
        // 赋值的话如果是newValue是对象，对象里面的属性也应该设置为响应式的
        self.walk(newValue)
        dep.notify()
      }


    })
  }
}